package com.aiatomic.couting.scan;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.aiatomic.couting.R;
import com.aiatomic.couting.Result;
import com.aiatomic.couting.ScanActivity;
import com.aiatomic.couting.models.TemplateEntity;
import com.aiatomic.couting.util.AppUtils;
import com.aiatomic.couting.util.ImageUtils;
import com.aiatomic.couting.util.OKHttpUtil;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.LoadingDialog;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FragmentScanBegin extends Fragment {
    private View view;
    private ScanActivity activity;
    private LoadingDialog dialog;
    private Handler handler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_scan_begin, container, false);
        activity = (ScanActivity) getActivity();
        dialog = new LoadingDialog(getActivity());
        bindEvent();
        return view;
    }

    private void bindEvent() {
        view.findViewById(R.id.txtAreaTools).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (view.findViewById(R.id.areaToolBar).getVisibility() == View.GONE) {
                    view.findViewById(R.id.areaToolBar).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.imgAreaTools).setSelected(true);
                } else {
                    view.findViewById(R.id.areaToolBar).setVisibility(View.GONE);
                    view.findViewById(R.id.imgAreaTools).setSelected(false);
                }
            }
        });
        view.findViewById(R.id.txtCountTools).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                scaning();

            }
        });
        View moreBottom = view.findViewById(R.id.moreBottomId);
        moreBottom.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.dl.openDrawer(activity.lv);
            }
        });
    }

    private void scaning() {
        //判断账号
//        if (AppUtils.currency_day <= 0) {
//            Toast.makeText(activity, "余额不足，请去商店购买!", Toast.LENGTH_LONG).show();
//            return;
//        }
        activity.scanImg.reScan();
        dialog.setMessage(getString(R.string.scaning));
        dialog.show();
        ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.counting));
        BitmapDrawable drawable = (BitmapDrawable) activity.getScanImg().getDrawable();
        final TemplateEntity curTpl = activity.getCurTpl();
        final String config = curTpl.getGroup_id() + "_" + curTpl.getSb_template_id() + File.separator + curTpl.gettKey();
        if (drawable != null && drawable.getBitmap() != null) {
            File tplFile = new File(SystemUtil.GetTemplateStoreDir(activity) + config);
            final Bitmap scan_img = drawable.getBitmap();
            final String tplPath = tplFile.getAbsolutePath();
            Thread countThread = new Thread(new Runnable() {
                @Override
                public void run() {
//                    JsonObject data = new JsonObject();
//                    data.addProperty("img", bitmapToBase64(scan_img));
//                    data.addProperty("type", 400);
//                    data.addProperty("config", config);
//                    JsonObject jsonObject = new JsonObject();
//                    jsonObject.addProperty("data", new Gson().toJson(data));
//                    RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(jsonObject))
                    String filePath = ImageUtils.saveBitmap(scan_img, getActivity());
                    OkHttpClient okHttpClient = OKHttpUtil.getUtil().getOkHttpClient();
                    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                    File file = new File(filePath);
                    builder.addFormDataPart("fileName", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));
                    builder.addFormDataPart("type", "400");
                    builder.addFormDataPart("config", "tpl_" + config);

                    Request request = new Request.Builder()
                            .url("http://3t2b390615.qicp.vip//uploadFile")
                            .post(builder.build())
                            .build();
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response execute = call.execute();
                        ResponseBody body = execute.body();
                        if (body != null) {
                            String string = body.string();
                            final Result result = new Gson().fromJson(string, Result.class);
                            if (result != null && result.success) {
                                final int ret = result.count;
                                Log.i("DEBUG", String.valueOf(ret));
                                Log.e("DEBUG", result.lastError);
                                if (ret == 0) {
                                    handler.post(new Runnable() {

                                        @Override
                                        public void run() {
                                            Toast.makeText(activity, "此模板不适用当前照片!", Toast.LENGTH_LONG).show();
                                            dialog.cancel();
                                            ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.count));
                                        }
                                    });
                                    return;
                                }
                                for (int i = 0; i < ret; i++) {
                                    Log.i("DEBUG", String.format("%d,%d,%d,%d,%d", result.paramArrayOfInt1[i], result.paramArrayOfInt2[i],
                                            result.paramArrayOfInt3[i], result.paramArrayOfInt4[i], result.paramArrayOfInt5[i]));
                                }
                                handler.postAtFrontOfQueue(new Runnable() {

                                    @Override
                                    public void run() {
                                        for (int i = 0; i < ret; i++) {
                                            ScanDrawable scanRet = new ScanDrawable(result.paramArrayOfInt5[i], result.paramArrayOfInt1[i], result.paramArrayOfInt2[i], result.paramArrayOfInt3[i], result.paramArrayOfInt4[i]);
                                            activity.scanImg.drawables.add(scanRet);
                                        }
                                        activity.frameROI.invalidate();
                                        activity.txtCountContainer.setVisibility(View.VISIBLE);
                                        activity.scanImg.reCount();
                                        FragmentScanEnd fragment = new FragmentScanEnd();
                                        activity.addFragment(fragment);
                                        activity.scanImg.invalidate();
                                        ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.count));
                                        dialog.cancel();
                                    }

                                });
                            } else {
                                handler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "此模板不适用当前照片!", Toast.LENGTH_LONG).show();
                                        dialog.cancel();
                                        ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.count));
                                    }
                                });
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        handler.post(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(activity, "此模板不适用当前照片!", Toast.LENGTH_LONG).show();
                                dialog.cancel();
                                ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.count));
                            }
                        });
                    }

//                    final int ret = CountingManager.count(scan_img, null, 400, tplPath);
//                    Log.i("DEBUG", String.valueOf(ret));
//                    Log.e("DEBUG", CountingManager.getLastError());
//                    if (ret == 0) {
//                        handler.post(new Runnable() {
//
//                            @Override
//                            public void run() {
//                                Toast.makeText(activity, "此模板不适用当前照片!", Toast.LENGTH_LONG).show();
//                                dialog.cancel();
//                                ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.count));
//                            }
//                        });
//
//                        return;
//                    }
//                    final int[] paramArrayOfInt1 = new int[ret];
//                    final int[] paramArrayOfInt2 = new int[ret];
//                    final int[] paramArrayOfInt3 = new int[ret];
//                    final int[] paramArrayOfInt4 = new int[ret];
//                    final int[] paramArrayOfInt5 = new int[ret];
//                    CountingManager.getResults(paramArrayOfInt1, paramArrayOfInt2, paramArrayOfInt3, paramArrayOfInt4,
//                            paramArrayOfInt5);
//                    for (int i = 0; i < ret; i++) {
//                        Log.i("DEBUG", String.format("%d,%d,%d,%d,%d", paramArrayOfInt1[i], paramArrayOfInt2[i],
//                                paramArrayOfInt3[i], paramArrayOfInt4[i], paramArrayOfInt5[i]));
//                    }
//                    handler.postAtFrontOfQueue(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            for (int i = 0; i < ret; i++) {
//                                ScanDrawable scanRet = new ScanDrawable(paramArrayOfInt5[i], paramArrayOfInt1[i], paramArrayOfInt2[i], paramArrayOfInt3[i], paramArrayOfInt4[i]);
//                                activity.scanImg.drawables.add(scanRet);
//							/*	paint.setColor(Color.GRAY);
//								paint.setAlpha(125);
//								draw_canvas.drawCircle(paramArrayOfInt1[i], paramArrayOfInt2[i], paramArrayOfInt3[i] / 2, paint);
//								paint.setColor(Color.RED);
//								paint.setAlpha(125);
//								paint.setTextAlign(Paint.Align.CENTER);
//								paint.setTextSize((int) (paramArrayOfInt3[i] * 0.8));
//								FontMetricsInt fontMetrics = paint.getFontMetricsInt();
//								int baseline = (fontMetrics.bottom + fontMetrics.top) / 2;
//								draw_canvas.drawText(String.valueOf(i + 1), paramArrayOfInt1[i], paramArrayOfInt2[i] - baseline, paint);
//								activity.getScanImg().setImageBitmap(alterBmp);*/
//                            }
//                            activity.frameROI.invalidate();
//                            activity.txtCountContainer.setVisibility(View.VISIBLE);
//                            activity.scanImg.reCount();
//                            FragmentScanEnd fragment = new FragmentScanEnd();
//                            activity.addFragment(fragment);
//                            activity.scanImg.invalidate();
//                            ((TextView) view.findViewById(R.id.txtCountTools)).setText(getString(R.string.count));
//                            dialog.cancel();
//                        }
//
//                    });

                }

            });
            countThread.start();
        } else {
            Toast.makeText(activity, "未找到图片!", Toast.LENGTH_LONG).show();
        }
        // 识别
        // dialog.cancel();
    }

    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
